
package org.apache.ocean;

import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.httpclient.NameValuePair;

/**
 *
 * @author jasonr
 */
public class URLParameters {
  public static Logger log = Logger.getLogger(URLParameters.class.getName());
  Map map;
  
  public URLParameters() {
    map = new HashMap();
  }
  
  public URLParameters(String str) throws Exception {
    map = javax.servlet.http.HttpUtils.parseQueryString(java.net.URLDecoder.decode(str, "UTF-8"));
  }
  
  public URL getURL(String name) {
    try {
      String str = get(name);
      if (str == null) return null;
      return new URL(str);
    } catch (Throwable throwable) {
      log.log(Level.SEVERE, "", throwable);
      return null;
    }
  }
  
  public String toURLEncoded() {
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    
    Set entrySet = map.entrySet();
    Iterator iterator = entrySet.iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      
      String name = (String)entry.getKey();
      String[] array = (String[])entry.getValue();
      for (String value : array) {
        pairs.add(new NameValuePair(name, value));
      }
    }
    
    String string = EncodingUtil.formUrlEncode((NameValuePair[])pairs.toArray(new NameValuePair[0]), "UTF-8");
    return string;
  }
  
  public CLong getLong(String name) {
    return ClusterUtil.parseLong(get(name));
  }
  
  public void set(String name, Object value) {
    if (value == null) return;
    map.put(name, new String[] {value.toString()});
  }
  
  public String toString() {
    String str = "";
    Set<Map.Entry> entrySet = map.entrySet();
    Iterator iterator = entrySet.iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      
      String name = (String)entry.getKey();
      String[] values = (String[])entry.getValue();
      str += name+": "+Arrays.asList(values);
      if (iterator.hasNext()) {
        str += ", ";
      }
    }
    return str;
  }
  
  public List<String> getValues(String name) {
    String[] array = (String[])map.get(name);
    if (array == null) return null;
    if (array.length == 0) return null;
    return Arrays.asList(array);
  }
  
  public String get(String name) {
    String[] array = (String[])map.get(name);
    if (array == null) return null;
    if (array.length == 0) return null;
    if (array.length > 0) return array[0];
    return null;
  }
}
